package com.qujia.station.controller;

import com.alibaba.fastjson.JSONObject;
import com.qujia.common.constant.HttpStatus;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.DateUtils;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.station.domain.OilEngine;
import com.qujia.station.domain.dto.OilEngineDto;
import com.qujia.station.domain.dto.OilEngineSumDto;
import com.qujia.station.domain.vo.EnterpriseAndStationVo;
import com.qujia.station.enums.OilEngineStatusEnum;
import com.qujia.station.service.IOilEngineService;
import com.qujia.station.service.IStationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/engine")
@Slf4j
@Api("油机数据接口")
public class OilEngineController extends BaseController {

    @Autowired
    private IOilEngineService oilEngineService;
    @Autowired
    private IStationService stationService;

    // 分页查询 油机数据列表  订单号不能超过11位
    @PostMapping("/list")
    @ApiOperation(value = "查询单个卡信息",httpMethod = "POST",response = OilEngineDto.class)
    public TableDataInfo getOilEngineList(@RequestBody(required = false) OilEngineDto oilEngineDto){
        OilEngineDto oilEngine = new OilEngineDto();
        if(Objects.nonNull(oilEngineDto)){
            log.info("getOilEngineList 请求参数：[{}]",JSONObject.toJSONString(oilEngineDto));
            BeanUtils.copyProperties(oilEngineDto,oilEngine);
        }
        if(StringUtils.isNotEmpty(oilEngine.getBeginTime()) && StringUtils.isNotEmpty(oilEngine.getEndTime())){
            long countDays = DateUtils.countDays(oilEngine.getBeginTime(), oilEngine.getEndTime());
            if(countDays > 31){
                TableDataInfo tableDataInfo = new TableDataInfo();
                tableDataInfo.setCode(HttpStatus.ERROR);
                tableDataInfo.setMsg("查询时间超过31天");
                tableDataInfo.setTotal(0l);
                tableDataInfo.setRows(null);
                return tableDataInfo;
            }
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        if(StringUtils.isNotEmpty(user.getUserLevel())){
            if(UserConstants.LEVEL_TWO.equals(user.getUserLevel())){
                oilEngine.setEnterpriseId(user.getEnterpriseId());
            }
            if(UserConstants.LEVEL_THREE.equals(user.getUserLevel())){
                oilEngine.setStationId(user.getStationId());
            }
            if (SecurityUtils.isPartner()) {
                EnterpriseAndStationVo itemIds = stationService.getItemIds(user);
                if (itemIds != null && itemIds.getEnterpriseIds().size()>0){

                    oilEngine.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());
                } else {
                    throw new CustomException(UserConstants.NO_ENTERPRISE);
                }
            }
        }
        if(Objects.nonNull(oilEngine) && StringUtils.isNotEmpty(oilEngine.getOrderNum())){
            // 订单号校验 不超过11位
            if(oilEngine.getOrderNum().length() > 11 ){
                TableDataInfo tableDataInfo = new TableDataInfo();
                tableDataInfo.setCode(HttpStatus.ERROR);
                tableDataInfo.setMsg("订单号超过11位");
                tableDataInfo.setTotal(0l);
                tableDataInfo.setRows(null);
                return tableDataInfo;
            }
        }
        startPage();
        log.info("getOilEngineList 请求参数：[{}]",JSONObject.toJSONString(oilEngine));
        List<OilEngine> oilEngineList = oilEngineService.selectOilEngine(oilEngine);
        if(CollectionUtils.isEmpty(oilEngineList)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(null);
            rspData.setTotal(0l);
            return rspData;
        }
        TableDataInfo dataTable = getDataTable(oilEngineList);
        List<OilEngine> rows = (List<OilEngine>) dataTable.getRows();
        List<OilEngineDto> oilEngineDtos = rows.stream().map(newOilEngine -> {
            OilEngineDto newOilEngineDto = new OilEngineDto();
            if (Objects.nonNull(newOilEngine)) {
                BeanUtils.copyProperties(newOilEngine, newOilEngineDto);
                return newOilEngineDto;
            }
            return null;
        }).collect(Collectors.toList());
        dataTable.setRows(oilEngineDtos);
        return dataTable;
    }

    // 合计统计
    @PostMapping("/oilEngineSum")
    @ApiOperation(value = "查询单个卡信息",httpMethod = "POST",response = OilEngineSumDto.class)
    public AjaxResult getOilEngineSum(@RequestBody(required = false) OilEngineDto oilEngineDto){
        OilEngineDto oilEngine = new OilEngineDto();
        if(Objects.nonNull(oilEngineDto)){
            BeanUtils.copyProperties(oilEngineDto,oilEngine);
        }
        if(Objects.nonNull(oilEngine) && StringUtils.isNotEmpty(oilEngine.getOrderNum())){
            // 订单号校验 不超过11位
            if(oilEngine.getOrderNum().length() > 11 ){
                return AjaxResult.error("订单号超过11位");
            }
        }
        if(StringUtils.isNotEmpty(oilEngine.getBeginTime()) && StringUtils.isNotEmpty(oilEngine.getEndTime())){
            long countDays = DateUtils.countDays(oilEngine.getBeginTime(), oilEngine.getEndTime());
            if(countDays > 31){
                return AjaxResult.error("查询时间超过31天");
            }
        }
        LoginUser currentUser = SecurityUtils.getLoginUser();
        SysUser user = currentUser.getUser();
        if(StringUtils.isNotEmpty(user.getUserLevel())){
            if(UserConstants.LEVEL_TWO.equals(user.getUserLevel())){
                oilEngine.setEnterpriseId(user.getEnterpriseId());
            }
            if(UserConstants.LEVEL_THREE.equals(user.getUserLevel())){
                oilEngine.setStationId(user.getStationId());
            }
            if (SecurityUtils.isPartner()) {
                EnterpriseAndStationVo itemIds = stationService.getItemIds(user);
                if (itemIds != null && itemIds.getEnterpriseIds().size()>0){

                    oilEngine.setEnterpriseIdListForAuthor(itemIds.getEnterpriseIds());
                } else {
                    throw new CustomException(UserConstants.NO_ENTERPRISE);
                }
            }
        }
        log.info("getOilEngineSum请求参数：[{}]", JSONObject.toJSONString(oilEngine));
        OilEngineSumDto oilEngineSum = oilEngineService.getOilEngineSum(oilEngine);

        return AjaxResult.success(oilEngineSum);
    }


    /**油机订单数据下所有油品*/
    @GetMapping("/oilName")
    @ApiOperation(value = "油机订单数据下所有油品",httpMethod = "GET",response = List.class)
    public AjaxResult getOilName(@RequestParam(value = "enterpriseId",required = false) Long enterpriseId){
        List<String> oilNameList = oilEngineService.getOilNameList(enterpriseId);
        return AjaxResult.success(oilNameList);
    }

    /**油机订单数据下所有油枪*/
    @GetMapping("/oilGun")
    @ApiOperation(value = "油机订单数据下所有油枪",httpMethod = "GET",response = List.class)
    public AjaxResult getOilGun(@RequestParam(value = "enterpriseId",required = false) Long enterpriseId){
        List<String> oilGunList = oilEngineService.getOilGunList(enterpriseId);
        return AjaxResult.success(oilGunList);
    }

    /**
     * 查询油机数据录入信息
     * 根据油枪和订单创建时间查询10分钟的订单
     * */
    @PostMapping("/listByGun")
    @ApiOperation(value = "查询油机数据录入信息", response = OilEngine.class)
    public AjaxResult getOilEngineList(@RequestBody(required = false) OilEngine oilEngine){
        log.info("请求查询油机数据录入信息getOilEngineList: [{}]", JSONObject.toJSONString(oilEngine));
        List<OilEngine> oilEngineList = oilEngineService.selectOilEngineList(oilEngine);
        log.info("响应查询油机数据录入信息getOilEngineList.size: [{}]", oilEngineList.size());
        return AjaxResult.success(oilEngineList);
    }

    /**
     * 公众号支付油机订单后，修改订单状态和记录支付时间
     * */
    @PostMapping("/payment")
    @ApiOperation(value = "修改订单状态和记录支付时间")
    public AjaxResult paymentOilOrder(@RequestBody OilEngineDto oilEngineDto){
        if(Objects.isNull(oilEngineDto) || Objects.isNull(oilEngineDto.getId())){
            return AjaxResult.error("请求参数异常");
        }
        log.info("paymentOilOrder 修改油机订单状态：[{}]",JSONObject.toJSONString(oilEngineDto));
        OilEngine oilEngine = new OilEngine();
        BeanUtils.copyProperties(oilEngineDto, oilEngine);
        oilEngine.setStatus(OilEngineStatusEnum.PAYMENT.getValue());
        oilEngine.setPayTime(new Date());
        oilEngine.setUpdateTime(new Date());
        int i = oilEngineService.updateOilEngine(oilEngine);
        if(i <= 0){
            return AjaxResult.error("支付状态修改失败");
        }
        return AjaxResult.success("支付成功");
    }

}
